package com.luxsoft.siipap.em.replica.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Map;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.JXTaskPane;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.gui.TableFormat;
import ca.odell.glazedlists.swing.EventTableModel;

import com.luxsoft.siipap.swing.utils.TaskUtils;
import com.luxsoft.siipap.swing.views2.AbstractInternalTaskView;

/**
 * TODO Cambiar a FilteredPanel
 * @author RUBEN
 *
 */
public class ExistenciasTaskView extends AbstractInternalTaskView implements ActionListener{
	
	private final ExistenciasModel model;
	private EventList source; 
	private JXTable grid;
	
	private JTextField inputField=new JTextField(10);
	
	public ExistenciasTaskView(final ExistenciasModel model){
		this.model=model;
	}
	
	private void initActions(){
		inputField.addActionListener(this);
	}
	
	protected TableFormat buildTableFormat() {
		DBFTableFormat tf=new DBFTableFormat();
		tf.setCampos("SASUCURSAL","SAARTICULO","SASALDINI","SASALDACT","SASALANTAJ","SASALDESAJ","SAULTOPER"
				    ,"SAFECHAJU","SASALDEXTE","SAFECHEXTE","SAINIDETAJ","SATOTPEDPE","SAULTPEDEL","SAULTENTPE"
				    ,"SATOTPEDCL","SAULTVENTA","SAACUVENTA","SAACUIMPVT","SAACUDEVVE","SAACUIMPDV","SAMOVXATE"
				    ,"SAUNIENCOR","SAMODENCOR");
		return tf;
	}
	
	private void initGlazedList(){
		source=new BasicEventList<Map>();
		
		final EventTableModel tm=new EventTableModel(source,buildTableFormat());
		grid=new JXTable();
		grid.setModel(tm);
	}

	public JComponent getControl() {
		initGlazedList();
		initActions();
		JScrollPane sp=new JScrollPane(grid);
		return sp;
	}
	
	public void refrescar(){
		SwingWorker<List<Map>, String> worker=new SwingWorker<List<Map>, String>(){
			protected List<Map> doInBackground() throws Exception {
				return model.busacarExistenciasDBF(inputField.getText());
			}
			protected void done() {
				source.clear();
				try {
					source.addAll(get());
				} catch (Exception e){
					e.printStackTrace();
				}finally{
					grid.packAll();
				}
			}
		};		
		TaskUtils.executeSwingWorker(worker);
	}

	public void actionPerformed(ActionEvent e) {
		refrescar();
		
	}

	@Override
	public void installFiltrosPanel(JXTaskPane filtros) {
		filtros.add(inputField);
	}
	
	

}
